import './css/user.css'
import { useState } from 'react';
import { useHistory } from 'react-router';
import AlterHeadShop from './AlterHeadShop';

const User = () => {
    const userObj = JSON.parse(sessionStorage['user']);
    var headshop = userObj.headshop;
    var src = `https:www.h5fd.xyz:2021/test/headImg/${headshop}`

    const [isAlt, setIsAlt] = useState(false);
    const [name,setName]=useState('')
    const [pass,setPass] = useState('');
    const [conn,setConn] = useState('');
    const history = useHistory();

    const alter = () => {
        setIsAlt(true);
    }

    const saveUser=()=>{
        if(name ==""){
            setName(JSON.parse(sessionStorage['user']).admin_name);
        }
        if(pass==""){
            setPass(JSON.parse(sessionStorage['user']).admin_passwd);
        }
        if(conn==""){
            setConn(JSON.parse(sessionStorage['user']).contact);
        }
        try{
            var obj={
                admin_name: name,
                admin_passwd: pass,
                concact: conn,
                admin_id:JSON.parse(sessionStorage['user']).admin_id
            }
    
            fetch('https:www.h5fd.xyz:2021/test/alterUser',{
                method: 'POST',
                body: JSON.stringify(obj)
            }).then(res=>res.json())
            .then(res=>{
                sessionStorage['user']=JSON.stringify(res);
                alert('修改成功');
                setIsAlt(false);
            })
        }catch(err){
            console.log(err);
            return 'tcx'
        }
    }

    const unLogin=()=>{
        sessionStorage.removeItem('user');
        history.replace('/');
    }

    return (
        <div className="bigUser">
            <img style={{width:100,height:100}}  src={src}></img>
            <br />
            <div className="userspan">{userObj.admin_name}</div>
            <button onClick={alter}>修改个人信息</button>
            {isAlt?
            <ul>
                <AlterHeadShop />
                <li>新昵称：<input className="userput" value={name} onChange={(e) => setName(e.target.value)}></input></li>
                <li>新密码：<input className="userput" value={pass} onChange={(e) => setPass(e.target.value)}></input></li>
                <li>修改联系方式：<input className="userput" value={conn} onChange={(e) => setConn(e.target.value)}></input></li>
                <li><button onClick={saveUser}>确定</button></li>
            </ul>:<></>}
            <button onClick={unLogin}>退出登录</button>
        </div>
    )
}

export default User;